//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Microsoft.Research.DataLayer
{
    public partial class ConnectionManagerDialogLite : Form, IConnectionManagerDialog
    {
        private ConnectionManagerBase connMgr;
        private Connection conn = null;
        private datasource.ConfigSources settings = null;
        private bool refreshing = false;

        public ConnectionManagerDialogLite()
        {
            InitializeComponent();
        }

        public ConnectionManagerDialogLite(ConnectionManagerBase connMgr,
            ref datasource.ConfigSources settings, bool allowConnect)
        {
            this.connMgr = connMgr;
            this.settings = settings;

            InitializeComponent();
            LoadConnections();
        }

        private void connect_Click(object sender, EventArgs e)
        {
            if (connList.Items.Count == 1)
            {
                connList.Items[0].Selected = true;
            }

            try
            {
                if ((null != connList.SelectedItems) && (connList.SelectedItems.Count > 0))
                {
                    // Try to get the connection
                    conn = connMgr.OpenConnection(((IConnMgrInfoParams)connList.SelectedItems[0].Tag));
                    Close();
                }
                else
                {
                    MessageBox.Show(Properties.Resources.SelectConnection, 
                        Properties.Resources.SelectConnectionTitle,
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (BackendStorageException ex)
            {
                MessageBox.Show("Cannot connect: " + ex.Message, "ERROR CONNECTING",
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

#pragma warning disable 0067
        // We don't save connections, so we do not use the OnSave event
        public event ConnectionManagerDialog.SaveHandler OnSave;
#pragma warning restore 0067

        public Connection Connection
        {
            get { return conn; }
        }

        private void LoadConnections()
        {
            connList.Items.Clear();
            provIcons.Images.Clear();

            foreach (ProviderPkgInfo prov in connMgr.Providers)
            {
                int logoIndex = -1;

                if (prov.Button.Logo != null)
                {
                    provIcons.Images.Add(prov.Button.Logo);
                    logoIndex = provIcons.Images.Count - 1;
                }

                foreach (IConnMgrInfoParams conn in prov.Presets)
                {
                    ListViewItem lvi = new ListViewItem();
                    lvi.ImageIndex = logoIndex;
                    lvi.SubItems.Add(prov.ProviderName);
                    lvi.SubItems.Add(conn.Name);
                    lvi.Tag = conn;
                    connList.Items.Add(lvi);
                }
            }

            if (connList.Items.Count > 0)
                connList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            else
                connList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

            defaultConnection.Enabled = (connList.Items.Count > 0 && connList.SelectedItems.Count > 0);
            connect.Enabled = (connList.Items.Count > 0);

        }

        private void connList_SelectedIndexChanged(object sender, EventArgs e)
        {
            connect.Enabled = (connList.SelectedItems != null);
            defaultConnection.Enabled = (connList.SelectedItems != null && connList.SelectedItems.Count > 0);

            // Get the default connection and check against the selected item
            IConnMgrInfoParams defaultConn = connMgr.DefaultConnection;
            refreshing = true;
            defaultConnection.Checked = (defaultConn != null && defaultConnection.Enabled &&
                (connList.SelectedItems != null && connList.SelectedItems.Count > 0 &&
                    defaultConn.Equals(connList.SelectedItems[0].Tag)));
            refreshing = false;
        }

        private void advanced_Click(object sender, EventArgs e)
        {
            // Let's disable our GUI
            this.Enabled = false;

            // We call our full GUI in advanced mode, and return the results to the caller
            ConnectionManagerDialog fullGUI = new ConnectionManagerDialog(connMgr, ref settings, true);
            fullGUI.OnSave += new ConnectionManagerDialog.SaveHandler(fullGUI_OnSave);
            DialogResult result = fullGUI.ShowDialog(this);

            if (result == DialogResult.OK)
            {
                DialogResult = result;
                conn = fullGUI.Connection;
                Close();
            }
            else
            {
                // Refresh our information and move on
                this.Enabled = true;
                LoadConnections();
            }
        }

        void fullGUI_OnSave(ConnectionManagerDialog.ConnSaveAction action)
        {
            if (OnSave != null)
                OnSave(action);
        }

        private void defaultConnection_CheckedChanged(object sender, EventArgs e)
        {
            if (refreshing)
                return;

            refreshing = true;

            if (defaultConnection.Checked)
            {
                // We are setting a new default connection
                if (connList.SelectedItems.Count == 1)
                {
                    IConnMgrInfoParams conn = connList.SelectedItems[0].Tag as IConnMgrInfoParams;
                    if (conn != null)
                    {
                        bool found = false;

                        foreach (ProviderPkgInfo prov in connMgr.Providers)
                        {
                            foreach (IConnMgrInfoParams preset in prov.Presets)
                            {
                                if (preset == conn)
                                {
                                    connMgr.DefaultConnection = preset;

                                    MessageBox.Show(string.Format(Properties.Resources.DefaultConnSetMessage,
                                            preset.Name, prov.ProviderName), Properties.Resources.DefaultConnSetTitle,
                                            MessageBoxButtons.OK, MessageBoxIcon.Information);

                                    found = true;
                                    break;
                                }
                            }

                            if (found)
                                break;
                        }

                    }
                }
            }
            else
            {
                // We are clearing a default connection
                connMgr.DefaultConnection = null;

                MessageBox.Show(Properties.Resources.DefaultConnClearMessage,
                        Properties.Resources.DefaultConnClearTitle,
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            refreshing = false;
        }

        private void ConnectionManagerDialogLite_Shown(object sender, EventArgs e)
        {
            if (connList.Items.Count == 0)
                advanced.PerformClick();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
